package com.lin.benchmade.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import com.lin.benchmade.Benchmade;
import com.lin.benchmade.utils.Hit;

public class AutocompleteServlet extends HttpServlet {
	private static final long serialVersionUID = -3184854652085346626L;
	private final Gson gson = new Gson();
	Benchmade bc;

	@Override
	public void init() throws ServletException {
		bc = Benchmade.getInstance();
		super.init();
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String k = req.getParameter("q");
		long st = System.currentTimeMillis();
		List<Hit> list = bc.autocomplete(k);
		long et = System.currentTimeMillis();
		resp.setContentType("application/json; charset=utf-8");
		PrintWriter out = resp.getWriter();
		int size = list.size();
		JsonObject result = new JsonObject();
		JsonArray jarray = new JsonArray();
		for (int i = size - 1; i >= 0; i--) {
			//jarray.add(new JsonPrimitive(list.get(i).getValue() + "\t" + list.get(i).getBoost()));
			jarray.add(new JsonPrimitive(list.get(i).getValue()));
		}
		result.add("autocomplete", jarray);
		out.write(gson.toJson(result));
	}

}
